﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using S7Project_One.Server;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace S7Project_One.MVVM
{
    public partial class LoginVM : ObservableObject
    {
        [ObservableProperty]
        private string userName = "";
        [ObservableProperty]
        private string password = "";
        [ObservableProperty]
        private string msg = "";
        [RelayCommand]
        private void Login(Button button) // 或者 object parameter
        {
            // 通过 button 获取需要的数据
            var window = Window.GetWindow(button); // 获取所属 Window
            if (window != null)
            {
                HandleLogin(window);
            }
        }
        [RelayCommand]
        private void Close(Button button) // 或者 object parameter
        {
            // 通过 button 获取需要的数据
            var window = Window.GetWindow(button); // 获取所属 Window
            if (window != null)
            {
                window.DialogResult = false;
            }
        }
        public void HandleLogin<T>(T Obj)
        {
            msg = "";
            try
            {
                if (LoginServer.CheckUserInfo(UserName, Password))
                {
                    LocalStorage.Set("UserName", UserName);
                    LocalStorage.Set("Password", Password);
                    (Obj as Window).DialogResult = true;
                }
                else
                {
                    throw new Exception("登录失败！用户名或密码错误!!");
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
            }
        }
    }
}
